package models

import (
	"github.com/beego/beego/v2/client/orm"
)

// GroupBuyStatistics 团购统计数据
type GroupBuyStatistics struct {
	TotalSales       int64                  `json:"total_sales" orm:"column(total_sales)"`             // 总销售额(分)
	TotalOrders      int64                  `json:"total_orders" orm:"column(total_orders)"`           // 总订单数
	SuccessRate      float64                `json:"success_rate" orm:"column(success_rate)"`           // 成团率
	ActivityCount    int64                  `json:"activity_count" orm:"column(activity_count)"`       // 活动数量
	SalesTrend       []SalesTrendData       `json:"sales_trend" orm:"-"`                               // 销售额趋势
	OrderTrend       []OrderTrendData       `json:"order_trend" orm:"-"`                               // 订单数趋势
	ActivityAnalysis []ActivityAnalysisData `json:"activity_analysis" orm:"-"`                         // 活动分析
	UserCount        int64                  `json:"user_count" orm:"column(user_count)"`               // 参与用户数
	AvgParticipation float64                `json:"avg_participation" orm:"column(avg_participation)"` // 人均参与次数
	AvgUserAmount    int64                  `json:"avg_user_amount" orm:"column(avg_user_amount)"`     // 人均消费金额(分)
	UserDistribution []UserDistributionData `json:"user_distribution" orm:"-"`                         // 用户分布
}

// SalesTrendData 销售额趋势数据
type SalesTrendData struct {
	Date   string `json:"date"`   // 日期
	Amount int64  `json:"amount"` // 金额(分)
	Type   string `json:"type"`   // 类型(总金额/实付金额)
}

// OrderTrendData 订单数趋势数据
type OrderTrendData struct {
	Date  string `json:"date"`  // 日期
	Count int64  `json:"count"` // 数量
	Type  string `json:"type"`  // 类型(总订单/成功订单)
}

// ActivityAnalysisData 活动分析数据
type ActivityAnalysisData struct {
	Id          int64   `json:"id"`           // 活动ID
	Name        string  `json:"name"`         // 活动名称
	OrderCount  int64   `json:"order_count"`  // 订单数
	SalesAmount int64   `json:"sales_amount"` // 销售额(分)
	SuccessRate float64 `json:"success_rate"` // 成团率
}

// UserDistributionData 用户分布数据
type UserDistributionData struct {
	Type  string `json:"type"`  // 类型
	Value int64  `json:"value"` // 数量
}

// GetGroupBuyStatistics 获取团购统计数据
func GetGroupBuyStatistics(startTime, endTime int64, activityId int64, franchiseId int64) (*GroupBuyStatistics, error) {
	o := orm.NewOrm()
	stats := &GroupBuyStatistics{}

	// 构建基础查询条件
	cond := orm.NewCondition()
	cond = cond.And("created_at__gte", startTime).And("created_at__lte", endTime)
	if activityId > 0 {
		cond = cond.And("activity_id", activityId)
	}

	// 加盟商权限过滤
	if franchiseId > 0 {
		cond = cond.And("franchise_id", franchiseId)
	}

	// 1. 获取总销售额和总订单数
	// 分别查询总销售额和总订单数
	var totalSalesMaps []orm.Params
	_, err := o.QueryTable(new(GroupBuyOrder)).
		SetCond(cond).
		Aggregate("sum(amount) as total").
		Values(&totalSalesMaps)
	if err == nil && len(totalSalesMaps) > 0 && totalSalesMaps[0]["total"] != nil {
		stats.TotalSales = totalSalesMaps[0]["total"].(int64)
	}

	var totalOrdersMaps []orm.Params
	_, err = o.QueryTable(new(GroupBuyOrder)).
		SetCond(cond).
		Aggregate("count(*) as total").
		Values(&totalOrdersMaps)
	if err == nil && len(totalOrdersMaps) > 0 && totalOrdersMaps[0]["total"] != nil {
		stats.TotalOrders = totalOrdersMaps[0]["total"].(int64)
	}

	// 2. 计算成团率
	var successOrders int64
	successOrders, _ = o.QueryTable(new(GroupBuyOrder)).
		SetCond(cond).
		Filter("group_status", GroupStatusSuccess).
		Count()
	if stats.TotalOrders > 0 {
		stats.SuccessRate = float64(successOrders) / float64(stats.TotalOrders)
	}

	// 3. 获取活动数量
	activityCond := orm.NewCondition().And("start_time__lte", endTime).And("end_time__gte", startTime)
	if franchiseId > 0 {
		activityCond = activityCond.And("franchise_id", franchiseId)
	}
	stats.ActivityCount, _ = o.QueryTable(new(GroupBuyActivity)).
		SetCond(activityCond).
		Count()

	// 4. 获取销售额趋势
	// TODO: 实现按日期统计的销售额趋势

	// 5. 获取订单数趋势
	// TODO: 实现按日期统计的订单数趋势

	// 6. 获取活动分析数据
	var activityAnalysis []ActivityAnalysisData

	// 构建SQL查询，添加加盟商过滤条件
	query := `
		SELECT 
			a.id,
			a.name,
			COUNT(o.id) as order_count,
			SUM(o.amount) as sales_amount,
			SUM(CASE WHEN o.group_status = ? THEN 1 ELSE 0 END) * 100.0 / COUNT(o.id) as success_rate
		FROM ss_group_buy_activity a
		LEFT JOIN ss_group_buy_order o ON a.id = o.activity_id
		WHERE o.created_at BETWEEN ? AND ?
	`
	args := []interface{}{GroupStatusSuccess, startTime, endTime}

	// 添加加盟商过滤条件
	if franchiseId > 0 {
		query += " AND a.franchise_id = ? "
		args = append(args, franchiseId)
	}

	query += `
		GROUP BY a.id, a.name
		ORDER BY sales_amount DESC
		LIMIT 10
	`

	_, err = o.Raw(query, args...).QueryRows(&activityAnalysis)
	stats.ActivityAnalysis = activityAnalysis

	// 7. 获取用户统计数据
	// 分别查询用户数、平均参与次数和平均消费金额
	var userCountMaps []orm.Params
	_, err = o.QueryTable(new(GroupBuyOrder)).
		SetCond(cond).
		Aggregate("COUNT(DISTINCT user_id) as total").
		Values(&userCountMaps)
	if err == nil && len(userCountMaps) > 0 && userCountMaps[0]["total"] != nil {
		stats.UserCount = userCountMaps[0]["total"].(int64)
	}

	if stats.UserCount > 0 {
		// 计算平均参与次数
		var orderCountMaps []orm.Params
		_, err = o.QueryTable(new(GroupBuyOrder)).
			SetCond(cond).
			Aggregate("COUNT(*) as total").
			Values(&orderCountMaps)
		if err == nil && len(orderCountMaps) > 0 && orderCountMaps[0]["total"] != nil {
			totalOrders := orderCountMaps[0]["total"].(int64)
			stats.AvgParticipation = float64(totalOrders) / float64(stats.UserCount)
		}

		// 计算人均消费金额
		var totalAmountMaps []orm.Params
		_, err = o.QueryTable(new(GroupBuyOrder)).
			SetCond(cond).
			Aggregate("SUM(amount) as total").
			Values(&totalAmountMaps)
		if err == nil && len(totalAmountMaps) > 0 && totalAmountMaps[0]["total"] != nil {
			totalAmount := totalAmountMaps[0]["total"].(int64)
			stats.AvgUserAmount = totalAmount / stats.UserCount
		}
	}

	return stats, nil
}
